#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
1688登录页面元素调试脚本
用于检查页面元素结构，特别是登录按钮
"""

import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from rich.console import Console

console = Console()

def debug_1688_login_page():
    """调试1688登录页面元素"""
    console.print("[bold blue]🔍 1688登录页面元素调试[/bold blue]")
    
    # 设置Chrome选项
    chrome_options = Options()
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-dev-shm-usage')
    chrome_options.add_argument('--disable-blink-features=AutomationControlled')
    chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
    chrome_options.add_experimental_option('useAutomationExtension', False)
    
    driver = None
    try:
        driver = webdriver.Chrome(options=chrome_options)
        driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
        
        # 访问1688登录页面
        console.print("[yellow]访问1688 PC端登录页面...[/yellow]")
        driver.get('https://login.1688.com/')
        time.sleep(8)  # 等待页面完全加载
        
        console.print("[blue]页面标题:[/blue]", driver.title)
        console.print("[blue]当前URL:[/blue]", driver.current_url)
        
        # 查找所有可能的按钮元素
        console.print("\n[yellow]🔍 查找所有按钮元素:[/yellow]")
        
        # 查找所有button标签
        buttons = driver.find_elements(By.TAG_NAME, "button")
        console.print(f"[green]找到 {len(buttons)} 个button元素:[/green]")
        for i, btn in enumerate(buttons[:10]):  # 只显示前10个
            try:
                text = btn.text.strip()
                btn_id = btn.get_attribute('id')
                btn_class = btn.get_attribute('class')
                btn_type = btn.get_attribute('type')
                console.print(f"  {i+1}. ID: {btn_id}, Class: {btn_class}, Type: {btn_type}, Text: '{text}'")
            except Exception as e:
                console.print(f"  {i+1}. 获取按钮信息失败: {e}")
        
        # 查找所有input[type=submit]元素
        submit_inputs = driver.find_elements(By.CSS_SELECTOR, "input[type='submit']")
        console.print(f"\n[green]找到 {len(submit_inputs)} 个submit input元素:[/green]")
        for i, inp in enumerate(submit_inputs):
            try:
                inp_id = inp.get_attribute('id')
                inp_class = inp.get_attribute('class')
                inp_value = inp.get_attribute('value')
                console.print(f"  {i+1}. ID: {inp_id}, Class: {inp_class}, Value: '{inp_value}'")
            except Exception as e:
                console.print(f"  {i+1}. 获取input信息失败: {e}")
        
        # 查找包含"登录"文本的元素
        console.print("\n[yellow]🔍 查找包含'登录'文本的元素:[/yellow]")
        login_elements = driver.find_elements(By.XPATH, "//*[contains(text(), '登录') or contains(text(), '登 录')]")
        console.print(f"[green]找到 {len(login_elements)} 个包含'登录'的元素:[/green]")
        for i, elem in enumerate(login_elements[:5]):  # 只显示前5个
            try:
                tag_name = elem.tag_name
                elem_id = elem.get_attribute('id')
                elem_class = elem.get_attribute('class')
                text = elem.text.strip()
                console.print(f"  {i+1}. Tag: {tag_name}, ID: {elem_id}, Class: {elem_class}, Text: '{text}'")
            except Exception as e:
                console.print(f"  {i+1}. 获取元素信息失败: {e}")
        
        # 检查是否有验证码
        console.print("\n[yellow]🔍 检查验证码元素:[/yellow]")
        captcha_elements = driver.find_elements(By.XPATH, "//*[contains(@class, 'captcha') or contains(@id, 'captcha') or contains(text(), '验证码')]")
        if captcha_elements:
            console.print(f"[red]⚠️  发现 {len(captcha_elements)} 个验证码相关元素[/red]")
        else:
            console.print("[green]✓ 未发现验证码元素[/green]")
        
        # 等待用户观察
        console.print("\n[blue]浏览器将保持打开30秒供观察...[/blue]")
        time.sleep(30)
        
    except Exception as e:
        console.print(f"[red]❌ 调试过程中出错: {e}[/red]")
    finally:
        if driver:
            driver.quit()
            console.print("[green]✓ 浏览器已关闭[/green]")

if __name__ == "__main__":
    debug_1688_login_page()